import {
  HttpApi
} from '../../model/index.js'
const httpApi = new HttpApi

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    imageList: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 拍摄照片
     */
    onAddImages: function() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['camera'],
        success: (res) => {
          // 本地图片地址
          const tempFilePaths = res.tempFilePaths;
          this.uploadQiniu(tempFilePaths);
        }
      })
    },
    /**
     * 图片上传七牛云
     */
    uploadQiniu(tempFilePaths) {
      let token = wx.getStorageSync('qiniuToken');
      wx.showLoading({
        title: '图片上传中',
      })
      wx.uploadFile({
        url: 'https://upload.qiniup.com',
        name: 'file',
        filePath: tempFilePaths[0],
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          token: token,
          key: `${Date.now()}weixin`
        },
        success: (res) => {
          let data = JSON.parse(res.data)
          if (!data.error) {
            //http://jylqndev.kaiwumace.com本地  http://jylqntest.kaiwumace.com测试  http://jylqn.kaiwumace.com生产
            this.data.imageList.push(`http://jylqn.kaiwumace.com/${data.key}`)
            this.setData({
              imageList: this.data.imageList
            })
          } else {
            wx.showToast({
              title: '系统出错了,请重新尝试',
              icon: "none"
            })
            httpApi.GetQiNiuToken().then(res => {
              wx.setStorageSync('qiniuToken', res.result)
            })
          }
          wx.hideLoading()
        }
      });
    },
    /**
     * 删除照片
     */
    onCancelImg: function(e) {
      let index = e.currentTarget.dataset.index;
      this.data.imageList.splice(index, 1)
      this.setData({
        imageList: this.data.imageList
      })
    },
    /**
     * 查看图片
     */
    onLookImg: function(e) {
      let index = e.currentTarget.dataset.index;
      wx.previewImage({
        current: this.data.imageList[index], // 当前显示图片的http链接
        urls: this.data.imageList // 需要预览的图片http链接列表
      })
    },
  }
})